package com.bayss.web.controller;

import com.bayss.core.constant.ResultMsg;
import com.bayss.core.model.ProcessInfo;
import com.bayss.core.service.activity.ObgRechargeActivityService;
import com.bayss.core.service.homepage.ActivityService;
import com.bayss.core.service.order.OrderService;
import com.bayss.core.service.pay.PayService;
import com.bayss.core.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * 支付
 *
 * @author yangjian
 */
@Slf4j
@RestController
public class PayController extends ApiBaseController {

    private final OrderService orderService;

    private final ActivityService activityService;

    private final PayService payService;
    private final ObgRechargeActivityService obgRechargeActivityService;

    @Autowired
    public PayController(OrderService orderService, ActivityService activityService, PayService payService,ObgRechargeActivityService obgRechargeActivityService) {
        this.orderService = orderService;
        this.activityService = activityService;
        this.payService = payService;
        this.obgRechargeActivityService = obgRechargeActivityService;
    }

    @RequestMapping("/pay/wx_notify.json")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        br.close();
        String notifyXml = sb.toString();
        log.info("recall info : " + notifyXml);

        Map<String, String> resMap = XmlUtil.xmlParse(notifyXml);
        String returnCode = resMap.get("return_code");
        String orderNo = resMap.get("out_trade_no");

        log.info("out_trade_no:" + orderNo);

        String resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";

        if("SUCCESS".equals(returnCode) && StringUtils.isNotBlank(orderNo)){
            // 业务逻辑
            if (orderNo.startsWith("at")) {
                // 活动报名支付
                activityService.activityPayCallBack(orderNo);
            }if (orderNo.startsWith("rc")) {
                // 充值支付
                obgRechargeActivityService.rechargeCallBack(orderNo);
            } else {
                // 订单
                ProcessInfo processInfo = ProcessInfo.builder()
                        .orderNo(orderNo)
                        .build();
                orderService.payAckOrder(processInfo);
            }
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
        }
        log.info("wx_notify_end : " + resXml);
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }

    /**
     * 退款 （上线后删除代码！！！！TODO）
     */
    @RequestMapping("/pay/tran.json")
    public ResultMsg tran() {
//        payService.transfersPay("oO2eX5HxAORgJAvewlSNPF5NLXk8", "yangjian123456", "100");
        return ResultMsg.success();
    }
}
